#include "http.h"
#include <QDebug>
#include "dcuinformation.h"

Http::Http(QObject *parent) : QObject(parent)
{
}

void Http::startRequst(QUrl url)
{
    downloadFile = new QFile(this);
    downloadFile->setFileName(UPDATEPATH);
    if (downloadFile->open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        qDebug() << "文件打开成功";
    }

    reply = networkManager.get(QNetworkRequest(url));
    connect(reply, &QNetworkReply::readyRead, this, &Http::httpReadyRead);
    connect(reply, &QNetworkReply::finished, this, &Http::httpFinished);
    connect(reply, &QNetworkReply::downloadProgress, this, &Http::httpdownloadProgress);
}

void Http::httpReadyRead()
{
    if (downloadFile) downloadFile->write(reply->readAll());
}

void Http::httpFinished()
{
    if (downloadFile)
    {
        downloadFile->close();
        delete downloadFile;
        downloadFile = NULL;
    }
    reply->deleteLater();
    reply = NULL;
    emit downloadFileFinished();
}

void Http::httpdownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    emit downloadProgress(bytesReceived, bytesTotal);
}
